package com.cpr.demo.filter;

import cn.hutool.core.util.StrUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.RequestFacade;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Map;

import static com.cpr.demo.constant.RedisKeyConstant.VISITOR_COUNT;
import static com.cpr.demo.constant.RedisKeyConstant.WHEN_I_WAS_30;

/**
 * @author Chen Panrui
 * created at 2021/8/31 16:50
 */
@Slf4j
@Component
@Setter
public class RedisCountFilter implements Filter {

    private StringRedisTemplate stringRedisTemplate;

    private String applicationName;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String url = ((RequestFacade) request).getRequestURL().toString(), merged;
        String[] split = url.split(applicationName);
        if(split.length!=2){
            log.info("不正常的访问--{}", url);
            chain.doFilter(request, response);
            return;
        }
        Long count = stringRedisTemplate.boundHashOps(VISITOR_COUNT).increment(merged = mergeUrlAndParam(split[1], request.getParameterMap()), 1L);
        stringRedisTemplate.boundHashOps(VISITOR_COUNT).expireAt(WHEN_I_WAS_30);
        log.info("访问次数{}--第{}次", merged, count);
        chain.doFilter(request, response);
    }

    private String mergeUrlAndParam(String url, Map<String, String[]> map){
        StringBuilder b = new StringBuilder();
        map.forEach((k,v)->{
            if(v!=null){
                for (String s : v) {
                    b.append("&").append(k);
                    if (!StrUtil.isBlank(s)) {
                        b.append("=").append(s);
                    }
                }
            } else {
                b.append("&").append(k);
            }
        });
        String r = b.toString().replaceFirst("&","?");
        return url + r;
    }

}
